<template>
  <div class="pdf_box">
    <div class="toolbar">
      <span class="viewFind" @click="find" title="搜索">
                  <img src="~@/assets/img/sousuo.png">
                </span>
      <span></span>
      <span v-if="config.fullscreen" @click="sendEmit('fullscreen')" title="全屏">
                  <img src="~@/assets/img/pdf/quanping.png">
                </span>
      <span v-if="config.fullscreen"></span>
      <span class="zoomOut" @click="zoomOut" title="缩小">
                  <img src="~@/assets/img/suoxiao.png">
                </span>
      <span></span>
      <span class="zoomIn" @click="zoomIn" title="放大">
                  <img src="~@/assets/img/fangda.png">
                </span>
      <span></span>
      <span class="scaleSelectContainer" title="选择比例">
                  <select class="scaleSelect" v-model="currScale" @change="scalechanged" data-l10n-id="zoom">
                    <option v-if="!item.isHide" :value="item.value"
                            v-for="item in scaleChangeOpts">{{item.label}}</option>
                  </select>
                </span>
      <span></span>
      <span class="pageRotateCcw" @click="pageRotateCcw" title="逆时针旋转">
                  <img src="~@/assets/img/xuanzhuan2.png">
                </span>
      <span></span>
      <span class="pageRotateCw" @click="pageRotateCw" title="顺时针旋转">
                  <img src="~@/assets/img/xuanzhuan1.png">
                </span>

      <span v-if="config.collect&&bookmark&&collectSrc"></span>
      <span v-if="config.collect&&bookmark&&collectSrc" @click="sendEmit('collect',{bookmark,nodeid:config.nodeid})" :title="collectTittle">
                  <img ref="collect" :src="collectSrc">
                </span>
    </div>
    <iframe :src="pdfUrl" frameborder="0"></iframe>
  </div>
</template>

<script>
  import { mapState } from 'vuex'

  const { util: { getRandomId, convertDataURI } } = require('../util')
  const EventEmitter = require('events').EventEmitter

  export default {
    name: 'CPdf',
    data () {
      return {
        pdfUrl: ``,
        id: getRandomId(),
        pdfWindow: null,
        eventBus: null,
        scaleChangeOpts: [

          { value: 'auto', label: '自动缩放' },
          { value: 'page-actual', label: '实际大小' },
          { value: 'page-fit', label: '适合页面' },
          { value: 'page-width', label: '适合页宽' },
          { value: '0.5', label: '50%' },
          { value: '0.75', label: '75%' },
          { value: '1', label: '100%' },
          { value: '1.25', label: '125%' },
          { value: '1.5', label: '150%' },
          { value: '2', label: '200%' },
          { value: '3', label: '300%' },
          { value: '4', label: '400%' },
          { value: '', label: '', isHide: true }
        ],
        currScale: 'auto',
        collectTittle: '添加书签',
        collectSrc: ''
      }
    },
    computed: {
      ...mapState({
        bookmarks: state => state.bookmark.bookmarks
      }),
      PDFViewerApplication () {
        return this.pdfWindow && this.pdfWindow.PDFViewerApplication
      },
      bookmark () {
        let temp = {}
        let bookmark = this.$store.getters.getBookmark(this.config.nodeid) || temp
        if (bookmark.bmid) {
          this.collectTittle = '删除书签'
          this.collectSrc =  '/static/img/collect_.png'
        } else {
          this.collectTittle = '添加书签'
          this.collectSrc = '/static/img/collect.png'
        }
        return bookmark
      }
    },
    created () {
      this.pdfUrl = `/static/pdfjs/web/viewer.html?id=${this.id}`
      this.eventBus = new EventEmitter()
    },
    mounted () {
      window.addEventListener(`initPdf_${this.id}`, this.initPdf)
    },
    methods: {
      sendEmit (eventName, data = '') {
        this.$emit('pdf_callback', { eventName, data })
      },
      initPdf (ev) {
        this.pdfWindow = ev.detail
        console.log('pdf初始化完成')
        this.eventBus.emit('init')

        window.removeEventListener(`initPdf_${this.id}`, this.initPdf)
      },
      awaitInit () {
        console.log('等待pdf初始化完成')
        return new Promise((resolve, reject) => {
          this.eventBus.once('init', resolve)
        })
      },
      async open (src) {
        try {
          console.log('判断pdf组件是否初始化完成')
          // 判断pdf组建是否已经初始化，如未初始化，则等待初始化完成
          this.PDFViewerApplication || await this.awaitInit()
          console.log('打开pdf')
          await this.PDFViewerApplication.open(convertDataURI(src))
          // this.PDFViewerApplication.pdfViewer.currentScaleValue = 'page-fit';
          this.currScale = 'auto'
        } catch (e) {
          console.error(e)
        }
      },
      setCurrScale () {
        let currScale = this.PDFViewerApplication.pdfViewer.currentScaleValue
        let isExist = this.scaleChangeOpts.findIndex(item => item.value === currScale) > -1
        let selectObj = this.scaleChangeOpts.find(item => 'isHide' in item)
        console.log(isExist)
        selectObj.isHide = isExist
        selectObj.value = ''
        if (!isExist) {
          selectObj.value = currScale
          selectObj.label = Math.round(currScale * 100) + '%'
        }
        this.currScale = currScale
      },
      /**
       * 放大
       */
      zoomIn () {
        this.PDFViewerApplication.zoomIn()
        this.setCurrScale()
      },
      /**
       * 缩小
       */
      zoomOut () {
        this.PDFViewerApplication.zoomOut()
        this.setCurrScale()
      },
      /**
       * 顺时针旋转
       */
      pageRotateCw () {
        this.PDFViewerApplication.rotatePages(90)
      },
      /**
       * 逆时针旋转
       */
      pageRotateCcw () {
        this.PDFViewerApplication.rotatePages(-90)
      },
      /**
       * 改变当前缩放比例
       * @param value
       */
      scalechanged (ev) {
        this.PDFViewerApplication.pdfViewer.currentScaleValue = this.currScale

        let selectObj = this.scaleChangeOpts.find(item => 'isHide' in item)
        selectObj.isHide = true
        selectObj.value = ''
      },
      /**
       * 查找条的显示与隐藏
       */
      find () {
        this.PDFViewerApplication.findBar.toggle()
      }
    },
    props: {
      config: {
        type: Object,
        default: () => {
          return {}
        }
      }
    }
  }
</script>

<style scoped>
  .pdf_box {
    width: 100%;
    height: 100%;
    position: relative;
  }

  .pdf_box .toolbar {
    height: 33px;
    left: 0;
    right: 0;
    position: absolute;
    z-index: 1;
    cursor: default;
    background-color: #e7f2f6;
    border-bottom: 1px solid #9abade;
    min-width: 325px;
  }

  .pdf_box embed,
  .pdf_box object,
  .pdf_box iframe {
    width: 100%;
    height: 100%;
  }

  .toolbar > span:nth-child(2n+1) {
    height: 24px;
    width: 45px;
    position: relative;
    display: inline-block;
    /*border-right: 1px solid #9abade;*/
    margin-top: 4px;
  }

  .toolbar > span:nth-child(2n) {
    display: inline-block;
    width: 1px;
    height: 20px;
    margin-top: 6px;
    background-color: #9abade;
  }

  .toolbar > span.scaleSelectContainer {
    width: 95px;
  }

  .toolbar > span > img {
    position: relative;
    height: 24px;
    width: 40px;
    padding: 4px 12px;
    margin: 0 2px;
  }

  .toolbar > span > select {
    position: relative;
    height: 20px;
    margin: 2px 8px;
    font-size: 13.3px !important;
  }

  .toolbar > span > img:hover {
    background-color: #9ED6F1;
  }

  .toolbar > span:nth-last-child(1) {
    border-right: none;
  }

</style>
